import os

import cv2
import aircv as ac
from PIL import ImageGrab

from basic.logger import logger


# print circle_center_pos
def draw_circle(img, pos, circle_radius, color, line_width):
    cv2.circle(img, pos, circle_radius, color, line_width)
    cv2.imshow('objDetect', imsrc)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

##
def screenshotAndSave(self):
    """屏幕截图"""
    # 1、用grab函数截图，参数为左上角和右下角左标
    # image = ImageGrab.grab((417, 257, 885, 569))
    im = ImageGrab.grab()
    if os.path.exists("temp.png"):
        os.remove("temp.png")
    else:
        logger.warning("要删除的文件不存在！")
    im.save('temp.png')

def find_position(target, template, left, top):
    """
    寻找target图片在template中的位置，返回应该点击的坐标。
    对比下面的方法,这个更加精确
	"""
    theight, twidth = target.shape[:2]
    # 执行模板匹配，采用的匹配方式cv2.TM_SQDIFF_NORMED
    result = cv2.matchTemplate(target, template, cv2.TM_SQDIFF_NORMED)

    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
    # 如果匹配度小于98%，就认为没有找到。
    if min_val > float(0.28):
        logger.debug("相似度不够:" + str(min_val))
        return None

    # 绘制矩形边框，将匹配区域标注出来

    # cv2.rectangle(template, min_loc, (min_loc[0] + twidth, min_loc[1] + theight), (0, 0, 225), 2)
    # cv2.imshow("MatchResult----MatchingValue="+strmin_val, template)
    # cv2.imwrite('1.png', template, [int(cv2.IMWRITE_PNG_COMPRESSION), 9])
    # cv2.waitKey()
    # cv2.destroyAllWindows()
    x = min_loc[0] + twidth // 2 + left
    y = min_loc[1] + theight // 2 + top
    logger.debug("匹配成功" + str(min_val) + ",当前坐标:("+str(x) + "," + str(y) + ")")
    return (x, y)


# 根据区域的截图，并返回矩形图片中的所有匹配的元素的下标
def find_button_list(module_dir, rect_image):
    pos_list = []
    images = os.listdir("./images/" + module_dir)
    for image in images:
        target = cv2.imread('./images/common/' + image)
        pos = find_position(target, rect_image, 0, 0)
        if pos:
            # TODO：根据image解析出坐标位置

            pos_list.append(pos)
    return pos_list


def findbtn(imtar, imsrc):
    pos = ac.find_template(imsrc, imtar)
    if pos:
        circle_center_pos = pos['result']
        x = int(circle_center_pos[0])
        y = int(circle_center_pos[1])
        return (x, y)
    else:
        return None
    # myssss = ','.join(myssss(i) for i in circle_center_pos)
    # print(myssss)


if __name__ == "__main__":
    imsrc = ac.imread('images/test/full.png')  # 来源图片
    imtar = ac.imread('images/test/new.png')  # 图片小部分
    # find the match position    匹配截图的坐标，并转换为int格式

    position = find_position(imtar, imsrc, 0, 0)
    # position = findbtn(imsrc,imtar)

    # 定义圆圈
    circle_radius = 30
    color = (0, 255, 0)
    line_width = 10

    # draw circle
    draw_circle(imsrc, position, circle_radius, color, line_width)
